package org.card.sqlparser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by card on 16/3/2.
 */
public class CreateSqlParser {

    private String tableNamePrefix;

    private String javaTableName;

    private List<SqlColumn> sqlColumns;

    private String tableName;

    public CreateSqlParser(String tableNamePrefix) {
        this.tableNamePrefix = tableNamePrefix;
        sqlColumns = new ArrayList<SqlColumn>();
    }

    public void parse(String sql){
        parseTableName(sql);
        parseColumn(sql);
    }

    public void getCreateClass() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("public class ").append(javaTableName).append(" {\n");
        for(SqlColumn sqlColumn : sqlColumns) {
            stringBuilder.append("\n\t").append("private ").append(sqlColumn.getJavaType())
                    .append(" ")
                    .append(sqlColumn.getJavaName()).append(";\n");
        }

        stringBuilder.append("}");
        System.out.println(stringBuilder.toString());
    }

    public void getInsertMapper() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("insert into ")
                .append(tableName).append("(");
        for (int i = 0; i< sqlColumns.size(); i++) {
            if(!sqlColumns.get(i).getJavaName().equalsIgnoreCase("id")) {
                stringBuilder.append(sqlColumns.get(i).getName());
                if (i < sqlColumns.size() - 1) {
                    stringBuilder.append(",");
                } else {
                    stringBuilder.append(")");
                }
            }
        }

        stringBuilder.append(" values (");

        for (int i = 0; i< sqlColumns.size(); i++) {
            if(!sqlColumns.get(i).getJavaName().equalsIgnoreCase("id")) {
                stringBuilder.append("#{");
                stringBuilder.append(sqlColumns.get(i).getJavaName());
                stringBuilder.append("}");
                if (i < sqlColumns.size() - 1) {
                    stringBuilder.append(",");
                } else {
                    stringBuilder.append(")");
                }
            }
        }

        System.out.println(stringBuilder.toString());
    }

    public void selectAll() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select ");
        for (int i = 0; i< sqlColumns.size(); i++) {
            stringBuilder.append(sqlColumns.get(i).getName());
            if (i < sqlColumns.size() - 1) {
                stringBuilder.append(" , ");
            }
        }
        stringBuilder.append(" from ");
        stringBuilder.append(tableName);
        System.out.println(stringBuilder.toString());
    }

    public int parseTableName(String sql) {
        Pattern pattern=Pattern.compile("create table[ ]+([`]?[\\w]+[`]?)",Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sql);
        while (matcher.find()) {
            tableName = matcher.group(1);
            javaTableName = tableName.replaceAll(tableNamePrefix, "");
            javaTableName = underlineToCamel(javaTableName);
            javaTableName = javaTableName.substring(0, 1).toUpperCase() + javaTableName.substring(1);
            return matcher.group().length();
        }
        return -1;
    }

    public void parseColumn(String sql) {
        Pattern pattern = Pattern.compile("([`]?[\\w]+[`]?)[ ]+(int|varchar|tinyint|datetime|integer|short|char)(\\W)",Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sql);
        while (matcher.find()) {
            String column = matcher.group(1);
            String type = matcher.group(2);
            sqlColumns.add(new SqlColumn(column, type));
        }
    }


    public static void main(String args[]) {
        CreateSqlParser createSqlParser = new CreateSqlParser("t_m_");
        createSqlParser.parse("CREATE TABLE `t_m_menu` (\n" +
                "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n" +
                "  `name` varchar(127) NOT NULL DEFAULT '',\n" +
                "  `url` varchar(255) NOT NULL DEFAULT '',\n" +
                "  `parent_id` int(11) NOT NULL,\n" +
                "  `type` tinyint(3) NOT NULL,\n" +
                "  PRIMARY KEY (`id`),\n" +
                "  KEY `parent_id` (`parent_id`),\n" +
                "  KEY `type` (`type`)\n" +
                ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        createSqlParser.getInsertMapper();
        createSqlParser.selectAll();
    }

    public static String underlineToCamel(String param){
        param = param.replaceAll("\\W", "");
        if (param==null||"".equals(param.trim())){
            return "";
        }
        int len=param.length();
        StringBuilder sb=new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c=param.charAt(i);
            if (c=='_'){
                if (++i<len){
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
